package io.renren.utils;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangheng on 2017/7/31.
 */
public class SerialNumber {


    private static final int MAX_VALUE=99999;
    private static final String FORMAT = "yyyy";
    private static final Format DF= new SimpleDateFormat(FORMAT);
    private static final byte[] lock = new byte[0];
    private String prefix = null;
    private Date date = null;
    private int number=1;
    private static Map<String, SerialNumber> map = new HashMap<String, SerialNumber>();

    private SerialNumber(String prefix,Date date){
        this.prefix = prefix;
        this.date = date;
    }

    public static SerialNumber newInstance(String prefix){
        Date date = new Date();
        return newInstance(prefix,date);
    }

    public static SerialNumber newInstance(String prefix,Date date){
        SerialNumber o = null;
        synchronized (lock) {
            String key = getKey(prefix, date);
            if(map.containsKey(key)){
                o = map.get(key);
                int number = o.getNumber();
                if(number<MAX_VALUE){
                    o.setNumber(number+1);
                }else {
                    o.setNumber(1);
                }

            } else {
                o = new SerialNumber(prefix,date);
                map.put(key, o);
            }
        }
        return o;
    }



    private static String getKey(String prefix,Date date){
        return prefix+format(date);
    }

    private static String format(Date date){
        return DF.format(date);
    }

    public String toString(){
        return  format(date) + "-" + String.format("%04d", number) + prefix ;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    public static void main(String[] args) {

        int es = Integer.valueOf("00032");

        String res = String.format("%05d", 22);
        System.out.println(res);
        es++;
        String str = String.valueOf(es);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5-str.length(); i++) {
            sb.append('0');
        }
        sb.append(str);
        System.out.println(sb);
    }
}
